package com.heatup.apt.api.controller;

import java.util.*;
import javax.servlet.http.*;

import com.heatup.apt.api.service.CouponService;
import com.heatup.apt.api.service.DataDictService;
import com.heatup.apt.common.constants.DataDictConstants;
import com.heatup.apt.common.constants.ErrorCodeConstants;
import com.heatup.apt.common.constants.OrderContants;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.druid.util.StringUtils;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.JsonTools;
import com.heatup.apt.common.util.RequestTools;
import com.heatup.apt.common.util.ResponseTools;
import com.heatup.apt.model.api.ApiResultModel;

/**
 * 优惠券业务控制器
 * @author Earvin
 *
 */
@Controller
@RequestMapping(value = "/coupon")
public class CouponController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CouponController.class);
	@Autowired
    CouponService couponService;

	@Autowired
    DataDictService dataDictService;
	

	@ResponseBody
	@RequestMapping(value = "/get_coupon_list", method = { RequestMethod.POST, RequestMethod.GET })
	public String getUserCouponList(HttpServletRequest request) {
		logger.info("=================== CouponController has method getCouponList is run : ");
		String callback = RequestTools.RequestString(request, "callback", "");
		String orderType = RequestTools.RequestString(request, "orderType", "");
		String amount = RequestTools.RequestString(request, "amount", "");
		int couponId = RequestTools.RequestInt(request, "couponId",0);
		int couponDetailStatus = RequestTools.RequestInt(request, "couponDetailStatus",0);  //0: 可用的优惠券. 1: 已使用的优惠券。 2:已过期的
 		ApiResultModel<Map<String,Object>> apiResultModel = new ApiResultModel();
		if (isLogined()) {
			Map<String, Object> paramsMap = new HashMap<>();
			paramsMap.put("user_id", this.getUserInfo().getId());
			// 订单类型转换优惠券限制使用
			if (!"".equals(orderType)) {
				if (OrderContants.OrderType.team_course.getType().equals(orderType)) {
					paramsMap.put("limit_team_course", "1");
				} else if (OrderContants.OrderType.pt.getType().equals(orderType)) {
					paramsMap.put("limit_secret_course", "1");
				} else if (OrderContants.OrderType.fun_camp.getType().equals(orderType)) {
					paramsMap.put("limit_camp_course", "1");
				} else if (OrderContants.OrderType.selffit.getType().equals(orderType)) {
					paramsMap.put("limit_self_course", "1");
				} else if(OrderContants.OrderType.physical_examination.getType().equals(orderType)){
				    //9
					paramsMap.put("limit_physical_examination_course","1");
				} else if(OrderContants.OrderType.secret_experience.getType().equals(orderType)){
				    //10
					paramsMap.put("limit_secret_experience_course","1");
				}
				else {
					paramsMap.put("limit_team_course", "0");
					paramsMap.put("limit_secret_course", "0");
					paramsMap.put("limit_camp_course", "0");
					paramsMap.put("limit_self_course", "0");
					paramsMap.put("limit_physical_examination_course","0");
					paramsMap.put("limit_secret_experience_course","0");
				}
			}
			if (!"".equals(orderType)) {
				paramsMap.put("orderType", orderType);
				Date nowDate = DateUtils.getDateShort(new Date());
				paramsMap.put("now_date", nowDate);
			}
			if(!"".equals(amount)){
				paramsMap.put("min_use_money", amount);
				
			}

			if(couponId>0){
				paramsMap.put("coupon_id",couponId);	
			}
			if(couponDetailStatus==0){  
				//0: 可用的优惠券.
    			paramsMap.put("is_valid", "1");     //有效的
    			paramsMap.put("is_used", "0");         //未使用的
			}else if(couponDetailStatus==1){  
				//1: 已使用的优惠券
    			paramsMap.put("is_used", "1");  //已使用的
			}else if(couponDetailStatus==2){
				//2:已过期的
    			paramsMap.put("is_used", "0");  //未使用的
    			paramsMap.put("is_valid", "0"); //无效的
			}
			logger.info("CouponController has method is getUserCouponList param is " + paramsMap);

            apiResultModel.setData(couponService.queryUserCouponList(paramsMap));
            apiResultModel.setRet(ApiResultModel.RET_SUCCESS);
		} else {
			apiResultModel.setErrorCode(ErrorCodeConstants.Code.USER_NOT_LOGIN.getCode());
			apiResultModel.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
			apiResultModel.setRet(ApiResultModel.RET_ERROR);
		}
		apiResultModel.setLogined(isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(apiResultModel), callback);
	}
	
	//兑换优惠券
	//ret: 0表示成功。 1表示已被兑换过。2:表示没有该兑换码。3:该券已失效。4.已领完。5,6,7 9: 其他错误。  请查看定义返回文件
	@ResponseBody
	@RequestMapping(value = "coupon_change", method={RequestMethod.POST, RequestMethod.GET})
	public String updateCourponChange(HttpServletRequest request){
		String change_code = RequestTools.RequestString(request, "change_code", "");  //要兑换的券的code: 可能是固定的码 也可能是随机的码
        String callback = RequestTools.RequestString(request, "callback", "");
        ApiResultModel model = new ApiResultModel();
        model.setLogined(isLogined());
        String msg = "";
        try {
        	if(isLogined() && !StringUtils.isEmpty(change_code)){
    			Map<String, Object> paramsMap = new HashMap<String, Object>();
    			paramsMap.put("change_code", change_code);  
    			paramsMap.put("user_id", this.getUserInfo().getId());
    			paramsMap.put("is_valid", "1"); //有效的
    			paramsMap.put("is_used", "0");  //未使用的
        			
    			model = couponService.changeCoupon(paramsMap);
        	}else{
        		model.setRet(ApiResultModel.RET_ERROR);
        	}
        	
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error(ErrorCodeConstants.Code.COUPON_NOT_FOUND.getMessage() + e.toString() + e.getCause(),e);
            model.setRet(ApiResultModel.RET_ERROR);
            model.setErrorCode(ErrorCodeConstants.Code.COUPON_NOT_FOUND.getCode());
            model.setMsg(ErrorCodeConstants.Code.COUPON_NOT_FOUND.getMessage());
        }
        return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
	}
	
	/**
	 * 根据批次ID获取兑换码
	 */
	@ResponseBody
	@RequestMapping(value = "query_coupon_code", method={RequestMethod.POST, RequestMethod.GET})
	public String getCouponCodeByCouponId(HttpServletRequest request){
		Integer couponId = RequestTools.RequestInt(request, "coupon_id", 0);  //要兑换的券的code: 可能是固定的码 也可能是随机的码
        String callback = RequestTools.RequestString(request, "callback", "");
		ApiResultModel model = new ApiResultModel();
		model.setLogined(isLogined());
		try{
			model =couponService.queryCouponCodeByCouponId(couponId);	
		}catch(Exception e){
			model.setRet(ApiResultModel.RET_ERROR);
			model.setMsg("根据批次ID获取兑换码异常");
			logger.error("根据批次ID获取兑换码异常:",e);
		}
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
	}

	/**
	 *
	 * 首次登陆送券活动
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(value = "/fristFreeCouponActivity", method={RequestMethod.POST, RequestMethod.GET})
	public String fristFreeCouponActivity(HttpServletRequest request, HttpServletResponse response){
		String callback = RequestTools.RequestString(request, "callback", "");
		ApiResultModel model = new ApiResultModel();
		if (!isLogined()) {
			model.setRet(ApiResultModel.RET_ERROR);
			model.setMsg(ErrorCodeConstants.Code.USER_NOT_LOGIN.getMessage());
			model.setLogined(false);
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
		}

		Integer activityId = null;
		List<DataDict> dataDictList = dataDictService.queryDataDicts(DataDictConstants.FREE_COUPON_ACTIVITY_ID);

		if (dataDictList != null) {
			DataDict dataDict = dataDictList.get(0);
			if (dataDict != null) {
				activityId = Integer.valueOf(dataDict.getDictCode());
			}
		}
		//未配置活动ID，则不送券
		if (activityId == null) {
			model.setRet(ApiResultModel.RET_ERROR);
			model.setMsg("未配置活动ID");
			model.setLogined(isLogined());
			return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
		}

		UserInfo userInfo = this.getUserInfo();
		try {
			Map<String,Object> respMap = couponService.freeFristCouponActivity(userInfo.getId(), activityId);;
			model.setData(respMap);
			model.setRet(ApiResultModel.RET_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("首次登陆送券活动异常：", e);
			model.setRet(ApiResultModel.RET_ERROR);
			model.setMsg("首次登陆送券活动异常");
		}
		model.setLogined(isLogined());
		return ResponseTools.CallBackResultJsonP(JsonTools.jsonSer(model), callback);
	}

}
